﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Pan
{
    public partial class disk : System.Web.UI.Page
    {
        protected int path;
        protected int page;
        protected int filecount;
        protected string breadcrumb;

        protected void Page_PreInit(object sender, EventArgs e)
        {
            Master.needLogin = true;
            Master.side = 1;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            bool redirect = false;
            // 参数检查
            try
            {
                this.path = Convert.ToInt32(Request.QueryString["path"]);
            }
            catch(Exception err)
            {
                this.path = -1;
            }
            finally
            {
                if (this.path < 0)
                {
                    this.path = Convert.ToInt32(Session["root"]);
                    redirect = true;
                }
            }
            try
            {
                this.page = Convert.ToInt32(Request.QueryString["page"]);
            }
            catch (Exception err)
            {
                this.page = -1;
            }
            finally
            {
                if (this.page < 1)
                {
                    this.page = 1;
                    redirect = true;
                }
            }
            if(!redirect)
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["PanConnectionString"].ToString();
                this.breadcrumb = "";
                try
                {
                    conn.Open();
                    // 计算面包屑
                    SqlCommand cmdList = new SqlCommand();
                    cmdList.Connection = conn;
                    cmdList.CommandType = CommandType.StoredProcedure;
                    cmdList.CommandText = "GetFileParent";
                    cmdList.Parameters.Add("@id", SqlDbType.Int).Value = this.path;
                    cmdList.Parameters.Add("@uid", SqlDbType.Int).Value = Master.uid;
                    SqlDataReader sdr = cmdList.ExecuteReader();
                    List<string[]> l = new List<string[]>();
                    while (sdr.Read())
                    {
                        l.Add(new string[2] { sdr["id"].ToString(), sdr["name"].ToString() });
                    }
                    sdr.Close();
                    // 目录不存在
                    if (l.Count == 0)
                    {
                        this.path = Convert.ToInt32(Session["root"]);
                        redirect = true;
                    }
                    else
                    {
                        int i = 0;
                        foreach (string[] s in l)
                        {
                            if (i < l.Count - 1)
                                breadcrumb += "<a href=\"/disk.aspx?path=" + s[0] + "\">" + s[1] + "</a>";
                            else
                                breadcrumb += "<a><cite>" + s[1] + "</cite></a>";
                            i++;
                        }
                        // 获取当前页文件总数
                        SqlCommand cmdCount = new SqlCommand();
                        cmdCount.Connection = conn;
                        cmdCount.CommandType = CommandType.StoredProcedure;
                        cmdCount.CommandText = "GetFileCount";
                        cmdCount.Parameters.Add("@pid", SqlDbType.Int).Value = this.path;
                        SqlDataReader sdrc = cmdCount.ExecuteReader();
                        if (sdrc.Read())
                        {
                            this.filecount = Convert.ToInt32(sdrc["count"]);
                        }
                        sdrc.Close();
                        // 页码越界检测
                        if (this.page > 1 && this.page > Math.Ceiling(this.filecount / 12.0))
                        {
                            this.page = (int)Math.Ceiling(this.filecount / 12.0);
                            redirect = true;
                        }
                    }
                }
                catch (Exception err)
                {
                    Master.RespLabel.Text = "<script>layui.use('layer',function(){layui.layer.alert('" + err.Message + "')})</script>";
                }
                finally
                {
                    conn.Close();
                }
            }
            // 重定向检查
            if (redirect)
            {
                Response.Redirect("/disk.aspx?path=" + this.path + "&page=" + this.page);
            }
        }

        private string RandomStr(int length)
        {
            const string dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = "";
            for (int i = 0; i < length; i++)
            {
                s += dict.Substring(r.Next(0, dict.Length - 1), 1);
            }
            return s;
        }

        protected void doPost_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PanConnectionString"].ToString();
            Master.RespLabel.Text = "";
            try
            {
                conn.Open();
                if (IsPostBack)
                {
                    if (Uploader.PostedFile != null && Uploader.PostedFile.ContentLength > 0)
                    {
                        string ext = System.IO.Path.GetExtension(Uploader.PostedFile.FileName).ToLower();
                        string filename = Session["uid"] + "_" +DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
                        string path = "./Uploads/" + filename;
                        Uploader.PostedFile.SaveAs(Server.MapPath(path));
                        SqlCommand cmdUpload = new SqlCommand();
                        cmdUpload.Connection = conn;
                        cmdUpload.CommandType = CommandType.StoredProcedure;
                        cmdUpload.CommandText = "NewFile";
                        cmdUpload.Parameters.Add("@uid", SqlDbType.Int).Value = Master.uid;
                        cmdUpload.Parameters.Add("@type", SqlDbType.Int).Value = 1;
                        cmdUpload.Parameters.Add("@pid", SqlDbType.Int).Value = this.path;
                        cmdUpload.Parameters.Add("@name", SqlDbType.VarChar, 255).Value = Uploader.PostedFile.FileName;
                        cmdUpload.Parameters.Add("@code", SqlDbType.VarChar, 255).Value = RandomStr(32);
                        cmdUpload.Parameters.Add("@fsize", SqlDbType.Float, 53).Value = Uploader.PostedFile.ContentLength / 1024.0;
                        cmdUpload.Parameters.Add("@location", SqlDbType.VarChar, 255).Value = filename;
                        if (cmdUpload.ExecuteNonQuery() > 0)
                        {
                            Response.Redirect("/disk.aspx?path=" + this.path);
                        }
                    }
                    else if (Method.Text == "mkdir" && Value.Text.Length > 0)
                    {
                        SqlCommand cmdMkdir = new SqlCommand();
                        cmdMkdir.Connection = conn;
                        cmdMkdir.CommandType = CommandType.StoredProcedure;
                        cmdMkdir.CommandText = "NewFile";
                        cmdMkdir.Parameters.Add("@uid", SqlDbType.Int).Value = Master.uid;
                        cmdMkdir.Parameters.Add("@type", SqlDbType.Int).Value = 0;
                        cmdMkdir.Parameters.Add("@pid", SqlDbType.Int).Value = this.path;
                        cmdMkdir.Parameters.Add("@code", SqlDbType.VarChar, 255).Value = "";
                        cmdMkdir.Parameters.Add("@name", SqlDbType.VarChar, 255).Value = Value.Text.Trim();
                        if (cmdMkdir.ExecuteNonQuery() > 0)
                        {
                            Response.Redirect("/disk.aspx?path=" + this.path);
                        }
                    }
                    else if (Method.Text == "delfile" && Value.Text.Length > 0)
                    {
                        string[] dellist = Value.Text.Trim().Split(',');
                        int count = 0;
                        foreach (string s in dellist)
                        {
                            SqlCommand cmdDelfile = new SqlCommand();
                            cmdDelfile.Connection = conn;
                            cmdDelfile.CommandType = CommandType.StoredProcedure;
                            cmdDelfile.CommandText = "DelFile";
                            cmdDelfile.Parameters.Add("@uid", SqlDbType.Int).Value = Master.uid;
                            cmdDelfile.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(s);
                            count += cmdDelfile.ExecuteNonQuery();
                        }
                        if (count > 0)
                        {
                            Response.Redirect("/disk.aspx?path=" + this.path);
                        }
                    }
                    else if (Method.Text == "mkshare" && Value.Text.Length > 0)
                    {
                        if(!Value.Text.Trim().StartsWith(",") && !Value.Text.Trim().EndsWith(",")){
                            string[] l = Value.Text.Split(',');
                            SqlCommand cmdGetfirst = new SqlCommand();
                            cmdGetfirst.Connection = conn;
                            cmdGetfirst.CommandType = CommandType.StoredProcedure;
                            cmdGetfirst.CommandText = "GetFileById";
                            cmdGetfirst.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(l[0]);
                            SqlDataReader sdr = cmdGetfirst.ExecuteReader();
                            if (sdr.Read())
                            {
                                string code = RandomStr(16);
                                SqlCommand cmdMkshare = new SqlCommand();
                                cmdMkshare.Connection = conn;
                                cmdMkshare.CommandType = CommandType.StoredProcedure;
                                cmdMkshare.CommandText = "ShareFile";
                                cmdMkshare.Parameters.Add("@uid", SqlDbType.Int).Value = Master.uid;
                                if(l.Length == 1)
                                    cmdMkshare.Parameters.Add("@name", SqlDbType.VarChar, 255).Value = sdr["name"];
                                else
                                    cmdMkshare.Parameters.Add("@name", SqlDbType.VarChar, 255).Value = sdr["name"] + "等" + l.Length + "个文件(夹)";
                                cmdMkshare.Parameters.Add("@code", SqlDbType.VarChar, 255).Value = code;
                                cmdMkshare.Parameters.Add("@fids", SqlDbType.VarChar, 255).Value = Value.Text.Trim();
                                sdr.Close();
                                if (cmdMkshare.ExecuteNonQuery() > 0)
                                {
                                    Master.RespLabel.Text = "<script>layui.use('layer',function(){layui.layer.alert('成功分享 " + l.Length + " 个文件(夹)，提取码为 " + code + "')})</script>";
                                }
                            }
                        }
                        else
                        {
                            Master.RespLabel.Text = "<script>layui.use('layer',function(){layui.layer.alert('分享错误，请重试')})</script>";
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Master.RespLabel.Text = "<script>layui.use('layer',function(){layui.layer.alert('" + err.Message + "')})</script>";
            }
            finally
            {
                conn.Close();
            }
            Method.Text = "";
            Value.Text = "";
        }
    }
}